package models

import "github.com/jinzhu/gorm"

type Tag struct{
	Model
	Name string `json:"name"`
	CreatedBy string `json:"created_by"`
	ModifiedBy string `json:"modified_by"`
	State int `json:"state"`
}

//标签列表
func GetTags(pageNum int,pageSize int,maps interface{})(tags []*Tag,err error)  {
	err = db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&tags).Error
	if err!=nil{
		return nil,err
	}
	return tags,nil
}

//总数
func GetTagTotal(maps interface{}) (count int,err error) {
	err=db.Model(&Tag{}).Where(maps).Count(&count).Error
	if err!=nil{
		return 0, err
	}
	return count,nil
}

//ExistTagByName检查是否有同名的标签
func ExistTagByName(name string) (bool,error) {
	var tag Tag
	err :=db.Select("id").Where("name = ? AND deleted_on = ?",name,0).First(&tag).Error
	if err!=nil && err!=gorm.ErrRecordNotFound{
		return false,err
	}
	if tag.ID>0{
		return true,nil
	}
	return false,nil
}

//ExistTagByID根据ID确定标记是否存在
func ExistTagByID(id int) (bool,error) {
	var tag Tag
	err :=db.Select("id").Where("id = ? AND deleted_on = ?",id,0).First(&tag).Error
	if err!=nil && err!=gorm.ErrRecordNotFound{
		return false,err
	}
	if tag.ID>0{
		return true,nil
	}
	return false,nil
}

//添加标签
func AddTag(name string, state int, createdBy string) error {
	if err :=db.Create(&Tag{
		Name: name,
		State: state,
		CreatedBy: createdBy,
	}).Error;err!=nil{
		return err
	}
	return nil
}
//修改标签
func EditTag(id int,data map[string]interface{}) error {
	if err:=db.Model(&Tag{}).Where("id = ? AND deleted_on = ?",id,0).Updates(data).Error;err!=nil{
		return err
	}
	return nil
}
//删除标签
//软删除
func DeleteTag(id int) error  {
	if err :=db.Where("id=? AND deleted_on = ? ",id,0).Delete(&Tag{}).Error;err!=nil{
		return err
	}
	return nil
}
// CleanAllTag clear all tag
//物理删除
func CleanAllTag() (bool, error) {
	if err := db.Unscoped().Where("deleted_on != ? ", 0).Delete(&Tag{}).Error; err != nil {
		return false, err
	}

	return true, nil
}


